package com.maxverse.boot.web2image.screenshot.core;

import com.microsoft.playwright.*;
import com.maxverse.boot.web2image.screenshot.config.PlaywrightConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class BrowserManager {
    private final PlaywrightConfig config;
    private final BlockingQueue<Browser> browserPool;
    private Playwright playwright;

    public BrowserManager(PlaywrightConfig config) {
        this.config = config;
        this.browserPool = new ArrayBlockingQueue<>(config.getBrowser().getPoolSize());
    }

    @PostConstruct
    public void init() {
        playwright = Playwright.create();
        for (int i = 0; i < config.getBrowser().getPoolSize(); i++) {
            Browser browser = createBrowser();
            browserPool.offer(browser);
        }
        log.info("Browser pool initialized with {} instances", config.getBrowser().getPoolSize());
    }

    @PreDestroy
    public void destroy() {
        browserPool.forEach(Browser::close);
        browserPool.clear();
        if (playwright != null) {
            playwright.close();
        }
        log.info("Browser pool destroyed");
    }

    public Browser acquireBrowser() throws InterruptedException {
        Browser browser = browserPool.poll(30, TimeUnit.SECONDS);
        if (browser == null) {
            throw new RuntimeException("Failed to acquire browser from pool");
        }
        return browser;
    }

    public void releaseBrowser(Browser browser) {
        if (browser != null) {
            browserPool.offer(browser);
        }
    }

    private Browser createBrowser() {
        BrowserType.LaunchOptions options = new BrowserType.LaunchOptions()
                .setHeadless(config.getBrowser().getLaunchOptions().isHeadless());
        return playwright.chromium().launch(options);
    }
} 